﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Http;
using MS.BasicData.Domain;
using MS.BasicData.Infrastructure;
using MS.BasicData.Infrastructure.IBaseRepository;
using System.Security.Claims;

namespace MS.BasicData.Read.API.Applications.Permissionss
{
    public class GetPermissionTreeRequestHandler : IRequestHandler<GetPermissionTreeRequestModel, ApiRestult>
    {

        private readonly IUserBaseRepository _userBaseRepository;

        private readonly IRoleBaseRepository _roleBAseRepository;

        private readonly IPermisBaseBaseRepository _permissionBAseRepository;

        private readonly IUserRoleBaseRepository _userRoleBaseRepository;

        private readonly IRolePermissionBaseRepository _rolePermissionBaseRepository;

        private readonly IHttpContextAccessor _httpContextAccessor;
       
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userBaseRepository"></param>
        /// <param name="roleBAseRepository"></param>
        /// <param name="permissionBAseRepository"></param>
        /// <param name="userRoleBaseRepository"></param>
        /// <param name="rolePermissionBaseRepository"></param>
        /// <param name="httpContextAccessor"></param>
        /// <param name="mapper"></param>
        public GetPermissionTreeRequestHandler(IUserBaseRepository userBaseRepository, IRoleBaseRepository roleBAseRepository, IPermisBaseBaseRepository permissionBAseRepository, IUserRoleBaseRepository userRoleBaseRepository, IRolePermissionBaseRepository rolePermissionBaseRepository, IHttpContextAccessor httpContextAccessor, IMapper mapper)
        {
            _userBaseRepository = userBaseRepository;
            _roleBAseRepository = roleBAseRepository;
            _permissionBAseRepository = permissionBAseRepository;
            _userRoleBaseRepository = userRoleBaseRepository;
            _rolePermissionBaseRepository = rolePermissionBaseRepository;
            _httpContextAccessor = httpContextAccessor;
            _mapper = mapper;
        }

        public Task<ApiRestult> Handle(GetPermissionTreeRequestModel request, CancellationToken cancellationToken)
        {
            throw new NotImplementedException();
        }
        //public async Task<ApiRestult> Handle(GetPermissionTreeRequestModel request, CancellationToken cancellationToken)
        //{
        //    ApiRestult result = new ApiRestult
        //    {
        //        isSuc = true,
        //        Code = Restult.Success,
        //        Message = "获取权限树成功",
        //    };

        //    try
        //    {
        //        var list = GetPermissionTree(0);

        //        // 检查list是否为null
        //        if (list == null)
        //        {
        //            result.Code = Restult.Fail;
        //            result.Message = "权限树获取失败";
        //            result.Data = null;
        //            return result;
        //        }

        //        var user =  _httpContextAccessor.HttpContext.User;
        //        var UserInfoId = user.FindFirst(type: ClaimTypes.NameIdentifier)?.Value;

        //        // 检查UserId是否为null
        //        if (string.IsNullOrEmpty(UserInfoId))
        //        {
        //            result.Code = Restult.Fail;
        //            result.Message = "用户ID不存在";
        //            result.Data = null;
        //            return result;
        //        }
        //        // 尝试解析UserId
        //        if (!int.TryParse(UserInfoId, out int userIdParsed))
        //        {
        //            result.Code = Restult.Fail;
        //            result.Message = "用户ID格式不正确";
        //            result.Data = null;
        //            return result;
        //        }

        //        // 当前用户对应的权限ID
        //        var userRoles = await _userRoleBaseRepository.GetAll(x => x.UserInfoId == int.Parse(UserInfoId));

        //        var roleIds = userRoles.Select(x => x.RoleId).ToArray();

        //        // 检查roleIds是否为空
        //        if (roleIds.Length == 0)
        //        {
        //            result.Code = Restult.Fail;
        //            result.Message = "用户没有角色";
        //            result.Data = list; // 返回原始权限树
        //            return result;
        //        }

        //        var userPermissions = await _rolePermissionBaseRepository.GetAll(x => roleIds.Contains(x.RoleId));

        //        var PermissionIds = userPermissions.Select(x => x.PermissionId).ToArray();

        //        // 过滤出当前用户的权限
        //        list = list.Where(x => PermissionIds.Contains(x.PermissionId)).ToList();

        //        result.Code = Restult.Fail;
        //        result.Message = "获取权限树成功";
        //        result.Data = list;

        //        return result;

        //    }
        //    catch (Exception ex)
        //    {
        //        result.Code = Restult.Fail;
        //        result.Message = "获取权限树失败";
        //    }
        //    return result;

        //}

        public List<GetPermissionTreeResponseModel> GetPermissionTree(int ParentId = 0)
        {
            var Tree = _permissionBAseRepository.GetAll(x => x.ParentId == ParentId);
            var result = _mapper.Map<List<GetPermissionTreeResponseModel>>(Tree);

            foreach (var item in result)
            {
                item.Children = GetPermissionTree(item.PermissionId);
            }
            return result;
        }

    }


    public class GetPermissionTreeRequestModel : IRequest<ApiRestult>
    {
        public int PageIndex { get; set; }
        public int PageSize { get; set; }
    }


    public class GetPermissionTreeResponseModel
    {
        public int PermissionId { get; set; }
        public string PermissionsName { get; set; } = string.Empty;
        public string Path { get; set; } = string.Empty;
        public string Name { get; set; } = string.Empty;
        public string Component { get; set; } = string.Empty;
        public IList<GetPermissionTreeResponseModel> Children { get; set; }
    }
}
